//code by Heskey0
//https://space.bilibili.com/455965619
//https://github.com/Heskey0

using System.CodeDom;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using UnityEngine;

namespace Teresa
{

    /// <summary>
    /// 表格的每行数据
    /// </summary>
    public class TableDatabase
    {
        public int ID;

    }


    /// <summary>
    /// 表格基类
    /// </summary>
    public class TableBase<TTableDatabase>
        where TTableDatabase : TableDatabase, new()
    {
        #region Singleton

        private TableBase<TTableDatabase> _instance = null;

        public TableBase<TTableDatabase> Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new TableBase<TTableDatabase>();
                }

                return _instance;
            }
        }

        #endregion

        Dictionary<int, TTableDatabase> _cache = new Dictionary<int, TTableDatabase>();

        protected void load(string tableName)
        {
            //创建文件夹
            StringBuilder tablePath = new StringBuilder(AppConfig.Path.Data.TablesPath);
            if (!Directory.Exists(tablePath.ToString()))
            {
                Directory.CreateDirectory(tablePath.ToString());
                Debug.Log("<color=orange>没有表格文件</color>::" + tablePath);
                return;
            }
            
            MemoryStream tableStream;
            // 读Project/Config
            var srcPath = tablePath.Append("/").Append(tableName);
            tableStream = new MemoryStream(File.ReadAllBytes(srcPath.ToString()));

            using (var reader = new StreamReader(tableStream, Encoding.GetEncoding("gb2312")))
            {
                //跳过注释（表中第一行）
                reader.ReadLine();

                //字段名
                var fileNameStr = reader.ReadLine();
                var fileNameArray = fileNameStr.Split(',');
                List<FieldInfo> allFileInfo = new List<FieldInfo>();
                foreach (var fieldName in fileNameArray)
                {
                    var fieldType = typeof(TTableDatabase).GetField(fieldName);
                    if (fieldType != null)
                    {
                        allFileInfo.Add(fieldType);
                    }
                    else
                    {
                        Debug.LogError("表中字段" + "" + "未在程序中定义" + fieldName);
                    }
                }


                //从第二行开始读
                var lineStr = reader.ReadLine();
                while (lineStr != null)
                {
                    TTableDatabase DB = readLine(allFileInfo, lineStr);

                    _cache[DB.ID] = DB;

                    lineStr = reader.ReadLine();
                }
            }

        }

        private static TTableDatabase readLine(List<FieldInfo> allFileInfo, string lineStr)
        {
            //从第二行开始读到的数据
            var itemStrArray = lineStr.Split(','); //分割
            var DB = new TTableDatabase();

            for (int i = 0; i < allFileInfo.Count; i++)
            {
                var field = allFileInfo[i];
                var data = itemStrArray[i];

                if (field.FieldType == typeof(string))
                {
                    field.SetValue(DB, data);
                }
                else if (field.FieldType == typeof(int))
                {
                    field.SetValue(DB, int.Parse(data));
                }
                else if (field.FieldType == typeof(float))
                {
                    field.SetValue(DB, float.Parse(data));
                }
                else if (field.FieldType == typeof(List<int>))
                {
                    var list = new List<int>();
                    foreach (var item in data.Split('$'))
                    {
                        list.Add(int.Parse(item));
                    }

                    field.SetValue(DB, list);
                }
            }

            return DB;
        }




        /// <summary>
        /// 获取表格数据_cache
        /// </summary>
        /// <param name="id"></param>
        public TTableDatabase this[int id]
        {
            get
            {
                TTableDatabase db;
                _cache.TryGetValue(id, out db);
                return db;
            }
        }


        public Dictionary<int, TTableDatabase> GetAll()
        {
            return _cache;
        }
    }

}